import os

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QSpinBox, QComboBox, \
    QPushButton, QSpacerItem, QSizePolicy, QDesktopWidget
import sys

from ClientUi.controls.CustomList import CustomList, CustomListItemType


class deviceManagerBaseDlg(QDialog):
    __topPanel = None
    __comboNum = None
    __midLayout = None
    __devList = None
    __saveBtn = None

    _clientUiPath = ''

    def __init__(self):
        super().__init__()
        currentPath = os.path.abspath(__file__)
        path = os.path.dirname(currentPath)
        #self.resize(800, 600)
        self.resize(1024, 800)
        self._clientUiPath = os.path.dirname(path)
        #self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        self.setSizeGripEnabled(True)
        self.__initUi()

    def __initUi(self):
        vl = QVBoxLayout()
        self._onInitTopWidget()

        # 中区域（相机列表）
        self.__midLayout = self.__createMidLayout()
        self.__midLayout.setContentsMargins(5,1,5,1)

        # 下区域 （保存按钮）
        bottomPanel = self.__createBottomWidget()

        if self.__topPanel is not None:
            vl.addWidget(self.__topPanel)

        vl.addLayout(self.__midLayout)
        vl.addWidget(bottomPanel)
        vl.setSpacing(0)
        vl.setContentsMargins(1,0,1,1)
        self.setLayout(vl)

        # 关联事件
        if self.__comboNum is not None:
            self.__comboNum.currentIndexChanged[int].connect(self.__devNumChanged)

        if self.__saveBtn is not None:
            self.__saveBtn.clicked.connect(self._onSave)

    def _createTopWidget(self, name: str, devMaxNum: int, currentNum: int, allowZero: bool = False):
        if self.__comboNum is not None:
            return None
        if currentNum > devMaxNum:
            print(f'wrong parameters, currentNum:{currentNum}, devMaxNum:{devMaxNum}')
            return None
        if currentNum < 0:
            print(f'wrong parameters, currentNum:{currentNum}, devMaxNum:{devMaxNum}')
            return None
        topPanel = QWidget()
        topPanel.setObjectName('DevManager_topPanel')
        hl_top = QHBoxLayout()
        topPanel.setLayout(hl_top)
        lb = QLabel(name)
        lb.setObjectName('devManagerLbNum')
        self.__comboNum = QComboBox()
        self.__comboNum.setObjectName('devManagerComboNum')
        hl_top.addWidget(lb)
        hl_top.addWidget(self.__comboNum)
        hl_top.addSpacerItem(QSpacerItem(0, 50, QSizePolicy.Expanding, QSizePolicy.Fixed))
        hl_top.addStretch()
        startNum = 1
        if allowZero is True:
            startNum = 0
        for i in range(startNum, devMaxNum + 1):
            self.__comboNum.addItem(str(i))
        self.__comboNum.setCurrentText(str(currentNum))
        self.__topPanel = topPanel

    def __createMidLayout(self):
        hl_mid = QHBoxLayout()
        self.__devList = CustomList()
        hl_mid.addWidget(self.__devList)
        self._onInitDevListHeader(self.__devList)
        devNum = 0
        if self.__comboNum is not None:
            devNum = int(self.__comboNum.currentText())

        self._onInitDevListRows(devNum, self.__devList)
        return hl_mid

    def __createBottomWidget(self):
        bottomPanel = QWidget()
        bottomPanel.setObjectName('DevManager_bottomPanel')
        hl_bottom = QHBoxLayout()
        bottomPanel.setLayout(hl_bottom)
        self._onAddWidgetsInBottomLeft(hl_bottom)
        hl_bottom.addSpacerItem(QSpacerItem(0, 50, QSizePolicy.Expanding, QSizePolicy.Fixed))
        self.__saveBtn = QPushButton('保存')
        hl_bottom.addWidget(self.__saveBtn)#, 0, Qt.AlignRight)
        return bottomPanel

    def _onInitTopWidget(self):
        print('you should inherit: _onInitTopWidget')
        print('and call :self.__createTopWidget')

    def _onAddWidgetsInBottomLeft(self, layout: QHBoxLayout):
        pass

    def _onInitDevListHeader(self, devList: CustomList):
        print('you should inherit: _onInitDevListHeader')
        print('and call :devList.SetColumnTitleAndTypes')

    def _onInitDevListRows(self, rowCount: int, devList: CustomList):
        print('you should inherit: _onInitDevListRows')
        print('and call: devList.setRowCount and devList.setRow')

    def _getDevList(self):
        return self.__devList

    def _getCurrentDevNum(self):
        if self.__comboNum is not None:
            return int(self.__comboNum.currentText())
        return 0

    def __devNumChanged(self, idx):
        self._onInitDevListRows(int(self.__comboNum.currentText()), self.__devList)
        app = QApplication.instance()
        # app.setStyleSheet(open(f'{self._clientUiPath}/styleSheet.qss', encoding='utf-8').read())
        ss = app.styleSheet()
        if len(ss) > 0:
            self.setStyleSheet(ss)

    def _onSave(self):
        print('you should inherit: _onSave')

    def SetMidLayoutMargins(self, left: int, top: int, right: int, bottom: int):
        self.__midLayout.setContentsMargins(left, top, right, bottom)

    def MoveWnd2Center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def SetSaveBtnName(self, name: str):
        self.__saveBtn.setText(name)

    def GetMidLayout(self):
        return self.__midLayout


if __name__ == '__main__':
    app = QApplication(sys.argv)
    try:
        current_path = os.path.abspath(__file__)
        path = os.path.dirname(current_path)
        path = os.path.dirname(path)
        app.setStyleSheet(open(f'{path}/styleSheet.qss', encoding='utf-8').read())
        window = deviceManagerBaseDlg()
        window.showNormal()
        sys.exit(app.exec_())

    except Exception as e:
        print(e)